package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * ClassName: CourseBaseInfoService
 * Package: com.xuecheng.content.service.impl
 * Description:
 *
 * @Author Endeavor-ZQB
 * @Create 2023/1/27 19:58
 * @Version 1.0
 */
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Autowired
    CourseMarketServiceImpl courseMarketService;



    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();

        //机构id
        queryWrapper.eq(CourseBase::getCompanyId,companyId);
        //构建查询条件，根据课程名称查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());

        //构造查询条件，根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());

        //构造查询条件，根据课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());

        //分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(),pageParams.getPageSize());
        //查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        //获取数据列表
        List<CourseBase> list = pageResult.getRecords();
        //获取数据总数
        long total = pageResult.getTotal();
        //构建结果集
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {

        //对参数进行合法性校验
//        if (StringUtils.isBlank(dto.getName())) {
//            //抛出异常
////            throw new RuntimeException("课程名称为空");
//            XueChengPlusException.cast("课程名称为空");
////            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
//        }
//
//        if (StringUtils.isBlank(dto.getMt())) {
////            throw new RuntimeException("课程分类为空");
//            XueChengPlusException.cast("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getSt())) {
////            throw new RuntimeException("课程分类为空");
//            XueChengPlusException.cast("课程分类为空");
//
//        }
//
//        if (StringUtils.isBlank(dto.getGrade())) {
////            throw new RuntimeException("课程等级为空");
//            XueChengPlusException.cast("课程等级为空");
//
//        }
//
//        if (StringUtils.isBlank(dto.getTeachmode())) {
////            throw new RuntimeException("教育模式为空");
//            XueChengPlusException.cast("教育模式为空");
//
//        }
//
//        if (StringUtils.isBlank(dto.getUsers())) {
////            throw new RuntimeException("适应人群为空");
//            XueChengPlusException.cast("适应人群为空");
//
//        }
//
//        if (StringUtils.isBlank(dto.getCharge())) {
////            throw new RuntimeException("收费规则为空");
//            XueChengPlusException.cast("收费规则为空");
//
//        }

        //对数据进行封装，调用mapper进行数据持久化
        CourseBase courseBase = new CourseBase();
//        将传入dto的数据设置到courseBase对象中
//        courseBase.setName(addCourseDto.getName());
//        courseBase.setMt(addCourseDto.getMt());
        //将dto中和courseBase一样的属性拷贝到courseBase中
        BeanUtils.copyProperties(dto,courseBase);
        //设置机构id
        courseBase.setCompanyId(companyId);
        //创建时间
        courseBase.setCreateDate(LocalDateTime.now());
        //审核状态默认为未提交
        courseBase.setAuditStatus("202002");
        //发布状态默认为未发布
        courseBase.setStatus("203001");

        //课程基本表插入一条记录
        int insert = courseBaseMapper.insert(courseBase);
        //获取课程id
        Long courseId = courseBase.getId();

        CourseMarket courseMarket = new CourseMarket();
        //将dto中和courseMarket一样的属性拷贝到courseMarket中
        BeanUtils.copyProperties(dto,courseMarket);
        courseMarket.setId(courseId);


        //检验如果课程为收费，价格必须输入
//        String charge = dto.getCharge();
//        if (charge.equals("201001")){ //收费
//            Float price = dto.getPrice();
//            if(price == null || price.floatValue()<=0){
////                throw new RuntimeException("课程设置了收费价格不能为空且必须大于0");
//                XueChengPlusException.cast("课程设置了收费价格不能为空且必须大于0");
//            }
//        }
        BeanUtils.copyProperties(dto,courseMarket);

        //课程营销表插入一条记录
        int insert1 = this.saveCourseMarket(courseMarket);
//        int insert1 = courseMarketMapper.insert(courseMarket);

        if (insert<=0 || insert1<=0){
//            throw new RuntimeException("添加课程失败");
            XueChengPlusException.cast("添加课程失败");

        }

        //组装返回的结果
        CourseBaseInfoDto courseBaseInfoDto = getCourseBaseInfoDto(courseId);

        return courseBaseInfoDto;
    }

    /**
     * 根据课程id查询课程的基本信息和营销信息
     * @param courseId  课程id
     * @return 课程的信息
     */
    public CourseBaseInfoDto getCourseBaseInfoDto(Long courseId){

        //课程的基本信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);

        //课程的营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        if(courseBase == null){
            return null;
        }

        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //根据课程分类的id查询课程分类的名称
        String mt = courseBase.getMt();
        String st = courseBase.getSt();

        CourseCategory mtCategory = courseCategoryMapper.selectById(mt);
        CourseCategory stCategory = courseCategoryMapper.selectById(st);

        if (mtCategory!=null){
            //分类名称
            String mtName = mtCategory.getName();
            courseBaseInfoDto.setMtName(mtName);
        }

        if (stCategory!=null){
            //分类名称
            String stName = stCategory.getName();
            courseBaseInfoDto.setStName(stName);
        }

        return courseBaseInfoDto;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBaseInfoDto(Long companyId, EditCourseDto dto) {

        //课程id
        Long courseId = dto.getId();
        CourseBase courseBaseUpdate = courseBaseMapper.selectById(courseId);
        if (courseBaseUpdate==null){
            XueChengPlusException.cast("课程不存在");
        }
        if (!companyId.equals(courseBaseUpdate.getCompanyId())){
            XueChengPlusException.cast("只允许修改本机构的课程");
        }

        //封装课程基本信息的数据
        BeanUtils.copyProperties(dto,courseBaseUpdate);
        //更新
        courseBaseUpdate.setChangeDate(LocalDateTime.now());
        int i = courseBaseMapper.updateById(courseBaseUpdate);

        //封装课程的营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if (courseMarket==null){
            courseMarket = new CourseMarket();
        }

        BeanUtils.copyProperties(dto,courseMarket);




        //检验如果课程为收费，价格必须输入
//        String charge = dto.getCharge();
//        if (charge.equals("201001")){ //收费
//            Float price = dto.getPrice();
//            if(price == null || price.floatValue()<=0){
////                throw new RuntimeException("课程设置了收费价格不能为空且必须大于0");
//                XueChengPlusException.cast("课程设置了收费价格不能为空且必须大于0");
//            }
//        }



        //对于营销信息有则更新，没有则添加
//        boolean saveOrUpdate = courseMarketService.saveOrUpdate(courseMarket);

        saveCourseMarket(courseMarket);

        //查询课程信息
        CourseBaseInfoDto courseBaseInfoDto = this.getCourseBaseInfoDto(courseId);
        return courseBaseInfoDto;
    }

    /**
     * @description  抽取课程营销校验及保存功能
     * @param courseMarket
     * @return
     */
    private int saveCourseMarket(CourseMarket courseMarket){
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
            XueChengPlusException.cast("请设置收费规则");
        }
        if(charge.equals("201001")){
            Float price = courseMarket.getPrice();
            if(price == null || price.floatValue()<=0){
                XueChengPlusException.cast("课程设置了收费价格不能为空且必须大于0");
            }
        }

        boolean b = courseMarketService.saveOrUpdate(courseMarket);
        return b?1:0;
    }
}
